import {
  createRouter,
  createWebHashHistory,
  type RouteRecordRaw,
} from "vue-router";
import Login from "@/views/Login.vue";
import store from "@/utils/store";
import Framework from "@/views/Framework.vue";

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    name: "Index",
    component: Framework,
    children: [
      {
        path: "goods/list",
        name: "GoodsList",
        component: () => import("../views/GoodsManager.vue"),
      },
      {
        path: "order/list",
        name: "OrderList",
        component: () => import("../views/OrderManager.vue"),
      },
      {
        path: "article/list",
        name: "ArticleList",
        component: () => import("../views/ArticleManager.vue"),
      },
      {
        path: "user/list",
        name: "UserList",
        component: () => import("../views/UserManager.vue"),
      },
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("../views/Dashboard.vue"),
      }
    ],
  },
  { path: "/login", name: "Login", component: Login },
];

const router = createRouter({
  // createWebHashHistory Hash模式，createWebHistory Histroy模式
  history: createWebHashHistory(),

  routes, // `routes: routes` 的缩写
});

router.beforeEach(async (to, from, next) => {
  // 过滤不需要token的页面
  if (to.name === "Login") {
    next();
  } else {
    if (store.getToken()) {
      console.log("已经登录");
      //   } else {
      //     console.log("已经有菜单了");
      //     // TODO 这里还需要处理缓存菜单时，也应该跳转到默认首页，而不是根目录
      next();
      //   }
    } else {
      console.log("未登录，跳转登录");
      next({
        name: "Login",
        query: {
          redirect: to.fullPath,
        },
      });
    }
  }

  // 根据权限判断，要进入的页面是否在权限内。
  // false 取消导航
  return false;
});
export default router;
